import sys
import os

from lib.net.wlan import wlan_esp32
import time


def scan_with_wlan_class():
    """使用项目WLAN类进行扫描"""
    print("使用WLAN类扫描WiFi网络...")

    # 创建WLAN实例
    wlan = wlan_esp32.WLAN()

    # 执行扫描
    networks = wlan.scan()

    if not networks:
        print("未发现WiFi网络")
        return []

    print(f"发现 {len(networks)} 个网络:")
    print("-" * 50)

    # 按信号强度排序
    networks.sort(key=lambda x: x[3], reverse=True)

    for i, net in enumerate(networks, 1):
        ssid = net[0].decode("utf-8") if net[0] else "隐藏网络"
        bssid = ":".join(["%02x" % b for b in net[1]])
        channel = net[2]
        rssi = net[3]
        security = net[4]

        # 信号强度百分比
        signal_percent = min(100, max(0, (rssi + 100) * 2))

        # 加密类型
        if security == 0:
            sec_type = "开放"
        elif security == 1:
            sec_type = "WEP"
        elif security == 2:
            sec_type = "WPA-PSK"
        elif security == 3:
            sec_type = "WPA2-PSK"
        elif security == 4:
            sec_type = "WPA/WPA2-PSK"
        else:
            sec_type = "未知"

        print(f"{i:2d}. {ssid}")
        print(
            f"    信号: {signal_percent:3d}% ({rssi:3d}dBm) | 加密: {sec_type} | 信道: {channel}"
        )
        print(f"    MAC: {bssid}")
        print()

    return networks


def continuous_scan(interval=5):
    """持续扫描"""
    print(f"开始持续扫描，间隔 {interval} 秒")
    print("按Ctrl+C停止")

    try:
        while True:
            scan_with_wlan_class()
            print(f"等待 {interval} 秒...")
            time.sleep(interval)
    except KeyboardInterrupt:
        print("\n扫描停止")


if __name__ == "__main__":
    print("ESP32 WiFi扫描工具 (使用WLAN类)")
    print("=" * 50)

    # 单次扫描
    scan_with_wlan_class()

    # 持续扫描 (取消注释启用)
    # continuous_scan(10)
